using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using log4net.Layout;
using NETL.Engine.Context;

namespace NETL.Engine
{
	public class Server
	{
		private static ILog myLogger;

		static Server()
		{
			FileInfo fInfo = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.xml"));
			if (fInfo.Exists)
			{
				XmlConfigurator.ConfigureAndWatch(fInfo);
			}
			else
			{
				ColoredConsoleAppender appender = new ColoredConsoleAppender();
				appender.Name = "FixedConsoleAppender";
				appender.Layout = new PatternLayout("%d [%t] %-5p %c [%x] - %m%n");
				appender.Threshold = Level.All;

				AddColorMapping(appender, Level.Error, ColoredConsoleAppender.Colors.Red);
				AddColorMapping(appender, Level.Warn, ColoredConsoleAppender.Colors.Yellow);
				AddColorMapping(appender, Level.Info, ColoredConsoleAppender.Colors.Green | ColoredConsoleAppender.Colors.HighIntensity);
				AddColorMapping(appender, Level.Debug, ColoredConsoleAppender.Colors.Green);

				appender.ActivateOptions(); 
				BasicConfigurator.Configure(appender);
			}

			myLogger = LogManager.GetLogger(typeof (Server));
		}

		private static void AddColorMapping(ColoredConsoleAppender appender, Level level, ColoredConsoleAppender.Colors color)
		{
			ColoredConsoleAppender.LevelColors mapping = new ColoredConsoleAppender.LevelColors();
			mapping.Level = level;
			mapping.ForeColor = color;
			appender.AddMapping(mapping);
		}


		public Server()
		{
		}

		public void Init()
		{
			myLogger.Info("Initializing...");
		}

		public void Start()
		{
			myLogger.Info("Starting NETL Engine...");
			ExecutionContext.Instance().Start();
		}

		public void Stop()
		{
			myLogger.Info("Stopping NETL Engine...");
			ExecutionContext.Instance().Stop();
		}

	}
}
